package com.ilas.service.impl;

import com.ilas.config.DynamicDataSource;
import com.ilas.dao.SysTenantDao;
import com.ilas.dao.TenantInfoDao;
import com.ilas.entity.SysTenant;
import com.ilas.service.ITenantService;
import com.ilas.sql.ScriptSql;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;

/**
 * <p>${Description}</p>
 *
 * @author luzck
 * @date 2021/4/1 16:43
 */
@Service
public class TenantServiceImpl implements ITenantService {

    @Resource
    private TenantInfoDao tenantInfoDao;

    @Resource
    private SysTenantDao sysTenantDao;

    @Resource
    private DynamicDataSource dynamicDataSource;

    /** 数据库连接url的基础 */
    private static final String BASE_URL = "jdbc:mysql://{0}:{1}/{2}?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai";

    /**
     * 判断租户编号是否存在
     *
     * @param code 租户编号
     * @return 是否有值
     */
    @Override
    public boolean isExsiteCode(String code) {
        SysTenant tenant = sysTenantDao.findByCode(code);
        return null != tenant;
    }


    /**
     * 根据租户名称查询租户信息
     *
     * @param name 租户名称
     * @return 是否有值
     */
    @Override
    public boolean findByName(String name) {
        SysTenant tenant = sysTenantDao.findByName(name);
        return tenant != null;
    }

    /**
     * 根据租户前端域名称查询租户信息
     *
     * @param domainName 租户前端域名
     * @return 是否有值
     */
    @Override
    public boolean findByDomainName(String domainName) {
        SysTenant tenant = sysTenantDao.findByDomainName(domainName);
        return tenant != null;
    }

    /**
     * 新增数据
     *
     * @param tenant 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysTenant insert(SysTenant tenant) throws Exception {
        if (StringUtils.isEmpty(tenant.getStatus())) {
            //默认状态：1-正常
            tenant.setStatus("1");
        }
        if (StringUtils.isEmpty(tenant.getDatasourceDriver())) {
            //默认mysql8.x驱动：com.mysql.cj.jdbc.Driver
            tenant.setDatasourceDriver("com.mysql.cj.jdbc.Driver");
        }
        if (StringUtils.isEmpty(tenant.getDatasourceType())) {
            //默认mysql
            tenant.setDatasourceType("MySQL");
        }
        if (StringUtils.isEmpty(tenant.getDatasourceUrl())) {
            //替换预设字段，变成完整的数据库连接url
            String url = MessageFormat.format(BASE_URL, tenant.getDatasourceIp(), tenant.getDatasourcePort(), tenant.getCode());
            tenant.setDatasourceUrl(url);
        }

        //获取租户使用期限
        //计算过期时间
        if (tenant.getUsageDays() != null) {
            Integer usageDays = tenant.getUsageDays();
            //从租户当前创建时间开始计算
            Date date = DateUtils.addDays(new Date(), usageDays);
            tenant.setExpiryDate(date);
        }
        //添加租户信息到sys_tenant表
        int result = sysTenantDao.insert(tenant);
        if (result > 0) {
            Properties prop = new Properties();
            prop.setProperty("driver", tenant.getDatasourceDriver());
            prop.setProperty("url", tenant.getDatasourceUrl());
            prop.setProperty("username", tenant.getDatasourceUsername());
            prop.setProperty("password", tenant.getDatasourcePassword());
            //以租户编号来创建租户库
            int total = sysTenantDao.createDatabase(tenant.getCode());
            if (total > 0) {
                //往数据库导入sql文件从而创建租户所需表
                ScriptSql.exeSQLScript(prop);
                //加载到动态数据源列表中
                dynamicDataSource.setDataSources(tenant);

                return tenant;
            }

        }
        return null;
    }

    /**
     * 加载全部数据
     *
     * @return 对象列表
     */
    @Override
    public List<SysTenant> queryAll() {
        return sysTenantDao.queryAll();
    }

    /**
     根据域名搜索租户编号
     @return 租户编号
     */
    @Override
    public String getTenantCodeByDomainName(String domainName) {
        //String domainName = SecurityUtils.getDomainName();
        // 根据域名搜索租户编号
        return sysTenantDao.findCodeByDomainName(domainName);
    }

    public void add() {
        /*try {
            Connection conn = master.getConnection();
            if (conn != null) {
                Statement stm = conn.createStatement();
                // 组织创建数据库sql
                StringBuilder sb = new StringBuilder("CREATE DATABASE ");
                sb.append(tenant.getTenantName()).append(";");

                //创建数据库
                int i = stm.executeUpdate(sb.toString());
                if (i > 0) {
                    System.out.println("创建成功！");
                    //打开 转向数据库
                    sb.setLength(0);
                    sb.append("USE ").append(tenant.getTenantName()).append(";");
                    stm.execute(sb.toString());
                    //执行脚本
                    System.out.println("开始导入数据！");
                    ScriptSql.exeSQLSript(tenant.getTenantName());
                    System.out.println("数据导入完成！");

                    MultipartDataSource multipartDataSource = new MultipartDataSource();
                    multipartDataSource.addDataSource(tenant.getTenantName(),ScriptSql.create(tenant));

                    tenant.setCreateDate(new Date());
                    tenant.setModifyDate(new Date());
                    int flag = tenantDao.insert(tenant);
                    if (flag > 0) {
                        return tenant;
                    }
                } else {
                    System.out.println("创建失败！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }
}
